package com.cy.pj.common.web;

import com.cy.pj.common.exception.DAOException;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @RestControllerAdvice相当于@ControllerAdvice + @ResponseBody
 * 异常处理级别：方法内try...catch... > 类中异常处理方法@ExceptionHandler > 全局类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ArithmeticException.class)
    public JsonResult doHandlerArithmeticException(ArithmeticException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return new JsonResult(e);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public JsonResult doHandlerIllegalArgumentException(IllegalArgumentException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return new JsonResult(e);
    }

    @ExceptionHandler(ServiceException.class)
    public JsonResult doHandlerServiceException(ServiceException e) {
        return new JsonResult(e);
    }

    @ExceptionHandler(DAOException.class)
    public JsonResult doHandlerServiceException(DAOException e) {
        return new JsonResult(e);
    }

    @ExceptionHandler(ShiroException.class)
    public JsonResult doHandleShiroException(ShiroException e) {
        JsonResult jr = new JsonResult();
        jr.setState(0);
        if(e instanceof UnknownAccountException) {
            jr.setMessage("账户不存在");
        } else if (e instanceof LockedAccountException) {
            jr.setMessage("账户已被禁用");
        } else if (e instanceof IncorrectCredentialsException) {
            jr.setMessage("密码不正确");
        } else if (e instanceof AuthorizationException) {
            jr.setMessage("没有此操作权限");
        } else {
            jr.setMessage("系统维护中");
        }
        e.printStackTrace();
        return jr;
    }
}
